/**
 * 
 */
package ads.engenharia.dal;

import java.sql.ResultSet;
import java.sql.SQLException;

import ads.engenharia.entity.Discipline;
import ads.engenharia.entity.Professor;

/**
 * @author Lanedraex
 *
 */
public class DisciplineProfessorHistory {

	private String sql;
	private String tableName = "Discipline_Professor_History";

	private EntityManager em = new EntityManager() {

		@Override
		public Object treatResultSet(ResultSet resultSet) throws SQLException {
			Discipline discipline = new Discipline();

			discipline.professor(searchDisciplineProfessor(discipline.id()));
			return discipline;
		}
	};

	/**
	 * Saves the discipline for the course in the junction table.
	 * 
	 * @param course
	 * @throws SQLException
	 */
	public void save(Discipline discipline) throws SQLException {

		sql = " insert into " + tableName + " ( discipline_id, professor_id ) ";

		em.executeQuery(sql, discipline.id(), discipline.professor().id());
	}

	/**
	 * 
	 * @param discipline
	 * @return
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public Professor searchDisciplineProfessor(Discipline discipline)
			throws SQLException {

		sql = " select distinct professor_id from " + tableName
				+ " where discipline_id = ? ";

		return (Professor) em.getSingleResult(sql, discipline.id());
	}

	/**
	 * 
	 * @param id
	 * @return
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public Professor searchDisciplineProfessor(int id) throws SQLException {

		sql = " select distinct professor_id from " + tableName
				+ " where discipline_id = ? ";

		return (Professor) em.getSingleResult(sql, id);
	}
}
